function getObjectURL(file) {
    var url = null;
    if (window.createObjcectURL != undefined) {
        url = window.createOjcectURL(file);
    } else if (window.URL != undefined) {
        url = window.URL.createObjectURL(file);
    } else if (window.webkitURL != undefined) {
        url = window.webkitURL.createObjectURL(file);
    }
    return url;
}

//桌面通知
function checkNotification(title, options){

    // 先检查浏览器是否支持
    if (!("Notification" in window)) {
        alert("This browser does not support desktop notification");
    }

    // 检查用户是否同意接受通知
    else if (Notification.permission === "granted") {
        // If it's okay let's create a notification
        setNoti();
    }

    // 否则我们需要向用户获取权限
    else if (Notification.permission !== 'denied') {
        Notification.requestPermission(function (permission) {
            // 如果用户同意，就可以向他们发送通知
            if (permission === "granted") {
                setNoti();
            }
        });
    }

    function setNoti(){
        var notification = new Notification(title, options);
        notification.onclick = function(e){
            window.open(notification.data.url, '_blank');
            notification.close();
        }
    }
    // 最后，如果执行到这里，说明用户已经拒绝对相关通知进行授权
}

//获取url中的参数
function getQueryString(name) {
    var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)"); // 匹配目标参数
    var result = window.location.search.substr(1).match(reg); // 对querystring匹配目标参数
    if (result != null) {
        return decodeURIComponent(result[2]);
    } else {
        return null;
    }
}

//去除数组中空元素
function removeEmpty(arr) {
    for (var i = 0; i < arr.length; i++) {
        if (arr[i].trim() == "") {
            arr.splice(i, 1);
            i--;
        }
    }
    return arr;
}

//补零
function todo(num) {
    if (isNaN(num)) return;
    return num > 9 ? num : "0" + num;
}

//表单校验错误提示
function formValidateTips(data, obj) {
    for (errName in data) {
        if (errName == 'code') {
            continue;
        }
        var errEle = $(obj).find(':input[name="' + errName.replace(/Msg/, '') + '"]').addClass('error');
        var msg = data[errName];
        if (errEle.length) {
            layer.tips(msg, errEle, {
                tips: [2, "#ffe9e8"],
                time: 5000,
                tipsMore: true
            });
        } else {
            layer.msg(msg);
        }
    }
}

function requestPage(options, callback) {
    var needLoad = options['needLoad'] || false === options['needLoad'] ? options['needLoad'] : true;
    $.ajax({
        url: options.url,
        data: options.data,
        dataType: 'json',
        beforeSend: function () {
            if (true === needLoad) {
                layer.load(2);
            }
        },
        success: function (data) {
            if (data.state === "fail" && data.msg === "notLogin") {
                options.dataContainer.html(options.notLoginMsg || "未登录");
                return;
            }
            var $totalRow = options.totalContainer ? options.totalContainer : $('#total-rows');
            var totalRow = parseInt(data['totalRow'] || 0);
            if ($totalRow.is("input")) {
                $totalRow.val(totalRow);
            } else {
                $totalRow.html(totalRow);
            }
            if (totalRow === 0) {
                options.dataContainer.html(options.notData);
                options.pageContainer.createPage({
                    pageCount: 0, seoUrl: options.seoUrl, current: 0, backFn: function (p) {
                    }
                });
                if (callback && (typeof callback === "function")) callback(data);
                return;
            }
            options.dataContainer.html(data.data);
            options.pageContainer.createPage({
                pageCount: data.totalPage, seoUrl: options.seoUrl, current: data.pageNumber, backFn: function (p) {
                    options.data.p = p;
                    $.ajax({
                        url: options.url,
                        data: options.data,
                        dataType: 'json',
                        beforeSend: function () {
                            layer.load(2);
                        },
                        success: function (data) {
                            layer.closeAll('loading');
                            if (data.state === "fail" && data.msg === "notLogin") {
                                options.dataContainer.html(options.notLoginMsg || "未登录");
                                return;
                            }
                            var totalRow = parseInt(data['totalRow'] || 0);
                            if ($totalRow.is("input")) {
                                $totalRow.val(totalRow);
                            } else {
                                $totalRow.html(totalRow);
                            }
                            if (totalRow === 0) {
                                options.dataContainer.html(options.notData);
                                return;
                            }
                            options.dataContainer.html(data.data);
                            if (callback && (typeof callback === "function")) callback(data);
                        }
                    });
                }
            });
            if (callback && (typeof callback === "function")) callback(data);
        },
        complete: function () {
            layer.closeAll('loading');
        }
    });
}

// 翻译成全拼方法函数
function toPinYin(sourceElement, targetElement) {
    if ($(sourceElement).is("select")) {
        $(sourceElement).on("change", function () {
            var sourceVal = $(sourceElement).val();
            var sourceText = $(sourceElement).find("option:selected").text();
            if (sourceVal) {
                var targetVal = pinyin.getFullChars(sourceText).substr(0, 64);
                if ($(sourceElement).attr('name') == 'authIdCardId') {
                    var strFront, strBack;
                    strFront = targetVal.substr(0, targetVal.indexOf(' '));
                    strBack = targetVal.substr(targetVal.indexOf(' ')).replace(/\s/g, '').toLowerCase();
                    strBack = strBack.charAt(0).toUpperCase() + strBack.substring(1);
                    targetVal = strFront + ' ' + strBack;
                } else if ($(sourceElement).attr('name') != 'authCompanyId') {
                    targetVal = targetVal.replace(/\s/g, '').toLowerCase();
                    targetVal = targetVal.charAt(0).toUpperCase() + targetVal.substring(1);
                }
                $(targetElement).val(targetVal);
            } else {
                $(targetElement).val("");
            }
        });
        $(sourceElement).trigger('change');
    } else {
        $(sourceElement).on("keyup", function () {
            var sourceVal = $(sourceElement).val();
            if (sourceVal) {
                var targetVal = pinyin.getFullChars(sourceVal).substr(0, 64);
                $(targetElement).val(targetVal);
            }
        });
        $(sourceElement).on('blur', function () {
            $(this).trigger('keyup');
        });
    }
}

function log(data) {
    console.log(data);
}

/**
 * 格式化金额
 *
 * @param s
 * @param n
 * @returns {string}
 */
function formatMoney(s, n) {
    var flag = n;
    n = n > 0 && n <= 20 ? n : 2;
    s = parseFloat((s + "").replace(/[^\d\.-]/g, "")).toFixed(n) + "";
    var l = s.split(".")[0].split("").reverse(),
        r = s.split(".")[1],
        t = "";
    for (i = 0; i < l.length; i++) {
        t += l[i] + ((i + 1) % 3 === 0 && (i + 1) !== l.length ? "," : "");
    }
    if (flag) {
        return '￥' + t.split("").reverse().join("") + "." + r;
    } else {
        return '￥' + t.split("").reverse().join("");
    }
}

/**
 * @param selectJson={all: selector, item: selector}
 */
function bindSelectAll(selectJson) {
    var $selectAll = $(selectJson.all);
    var $selectItem = $(selectJson.item);

    $selectAll.on('click', function () {
        if ($(this).is(':checked')) {
            $selectItem.not(':disabled').prop('checked', true);
        } else {
            $selectItem.not(':disabled').prop('checked', false);
        }
    });

    $selectItem.on('click', function () {
        var selectItem = $selectItem.not(':disabled');
        var selectCount = selectItem.filter(":checked").length;
        if (selectCount === selectItem.length) {
            $selectAll.prop('checked', true);
        } else {
            $selectAll.prop('checked', false);
        }
    });
}

/**
 * @param selectJson
 */
function batchSelect(selectJson) {
    var name = selectJson.name;
    var $type = $("#" + (selectJson.id ? selectJson.id : name));
    var $allType = $("[data-" + name + "]");
    var $typeCheckbox = $("[name=" + name + "]");

    $typeCheckbox.on("click", function () {
        if ($typeCheckbox.filter(":checked").length > 0) {
            $type.removeAttr("name").val("");
            $allType.removeClass("active");
        } else {
            $type.attr("name", name).val("all");
            $allType.addClass("active");
        }
    });

    $allType.on("click", function () {
        $allType.addClass("active");
        $typeCheckbox.prop("checked", false);
        $type.attr("name", name).val("all");
    });
}

/**
 * 检查短信验证码或操作安全码
 *
 * @returns {boolean}
 */
function checkAuthCodeAndSafeCode() {
    var objAuthCode = $('#authCode');
    var objSafeCode = $('#safeCode');
    if (objAuthCode.length > 0 && !objAuthCode.val()) {
        layer.msg('验证码不能为空!', {time:1500});
        return false;
    }

    if (objSafeCode.length > 0 && !objSafeCode.val()) {
        layer.msg('操作安全码不能为空!', {time:1500});
        return false;
    }

    return true;
}

$(function () {
    $.fn.serializeJson = function () {
        var serializeObj = {};
        var array = this.serializeArray();
        var str = this.serialize();
        $(array).each(function () {
            if (serializeObj[this.name]) {
                if ($.isArray(serializeObj[this.name])) {
                    serializeObj[this.name].push(this.value);
                } else {
                    serializeObj[this.name] = [serializeObj[this.name], this.value];
                }
            } else {
                serializeObj[this.name] = this.value;
            }
        });
        return serializeObj;
    };

    // 排序
    $(".sort_style").on("click", function () {
        var sortField = $('[name="sortField"]');
        var sortMethod = $('[name="sortMethod"]');
        var field = $(this).data('field');
        var firstSortWay = $(this).data('firstSortWay');
        var _this = $(this).find("i");
        var clazz = _this.prop("class");
        $(this).closest('tr').find('.sort_style i').prop('class', 'def');
        sortField.val(field);
        if (clazz === "def"){
            if(firstSortWay === "desc") {
                _this.prop("class", "desc");
                sortMethod.val('desc');
            } else {
                _this.prop("class", "asc");
                sortMethod.val('asc');
            }
        }
        if (clazz === "desc"){
            _this.prop("class", "asc");
            sortMethod.val('asc');
        }
        if (clazz === "asc") {
            _this.prop("class", "desc");
            sortMethod.val('desc');
        }
    });

    // 登录信息下拉
    $('.signIn_show').on('mouseenter', function () {
        var that = $(this);
        that.addClass('current');
        // $.ajax({
        //     url: '/get/account',
        //     dataType: 'json',
        //     success: function (data) {
        //         if (data.state == "ok") {
        //             that.find('.balance span').html('￥' + data.account.balance);
        //         }
        //     }
        // });
    }).on('mouseleave', function () {
        $(this).removeClass('current');
    });

    //左侧导航
    $('.main_slidebar li > a').on('click', function () {
        if(!$('.control_panel').hasClass('subnav_expand')) {
            var that = $(this);
            var parent = that.parent('li');
            if (parent.hasClass('active')) {
                parent.removeClass('active');
                parent.find('dl').slideUp();
            } else {
                parent.addClass('active').siblings('li').removeClass('active');
                that.closest('ul').find('dl').slideUp();
                that.next('dl').slideDown();
            }
        }
    });

    // 导航下拉菜单
    $('.mainNav_container nav > ul > li').hover(
        function () {
            $(this).find('.dropdown').stop(false, true).slideDown();
        }, function () {
            $(this).find('.dropdown').stop(false, true).slideUp();
        });

    //表格域名选择
    $('.select_all, #select-all').on('click', function () {
        var checkboxs = $(this).closest('.table_style').find('.select_item');
        if ($(this).is(':checked')) {
            checkboxs.not(':disabled').prop('checked', true);
            $('.select_all, #select-all').prop('checked', true);
        } else {
            checkboxs.not(':disabled').prop('checked', false);
            $('.select_all, #select-all').prop('checked', false);
        }
    });

    $('.table_style').on('click', '.select_item', function () {
        var parent = $(this).closest('.table_style');
        var selectItem = parent.find('.select_item').not(':disabled');
        var selectAll = parent.find('.select_all');
        var count = selectItem.filter(":checked").length;
        if (count === selectItem.length) {
            selectAll.prop('checked', true);
            $('#select-all').prop('checked', true);
        } else {
            selectAll.prop('checked', false);
            $('#select-all').prop('checked', false);
        }
    });
    //去除表单验证错误样式
    $(document).on('focus', ':input.error', function () {
        $(this).removeClass('error');
    });
    $(document).on('change', 'select.error', function () {
        $(this).removeClass('error');
    });

    Date.prototype.format = function (fmt) {
        var o = {
            "M+": this.getMonth() + 1,                 //月份
            "d+": this.getDate(),                    //日
            "h+": this.getHours(),                   //小时
            "m+": this.getMinutes(),                 //分
            "s+": this.getSeconds(),                 //秒
            "q+": Math.floor((this.getMonth() + 3) / 3), //季度
            "S": this.getMilliseconds()             //毫秒
        };
        if (/(y+)/.test(fmt)) {
            fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
        }
        for (var k in o) {
            if (new RegExp("(" + k + ")").test(fmt)) {
                fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
            }
        }
        return fmt;
    };

    //判断当前时间段
    var hours = new Date().getHours();
    var text = '';
    if (hours >= 0 && hours <= 10) {
        text = '早上好';
    } else if (hours > 10 && hours <= 14) {
        text = '中午好';
    } else if (hours > 14 && hours <= 18) {
        text = '下午好';
    } else if (hours > 18 && hours <= 24) {
        text = '晚上好';
    }
    $("#current_time_state").html(text);
});
